package com.taskmanager.controller;

import com.taskmanager.dto.TimeRecordRequest;
import com.taskmanager.dto.TimeRecordResponse;
import com.taskmanager.dto.TimerStatistics;
import com.taskmanager.service.TimerService;
import com.taskmanager.util.ApiResponse;
import com.taskmanager.util.ResponseUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.time.LocalDate;
import java.util.List;

/**
 * 计时器控制器
 * 处理计时器相关的HTTP请求
 */
@RestController
@RequestMapping("/api/timer")
public class TimerController {
    
    @Autowired
    private TimerService timerService;
    
    /**
     * 开始计时
     * POST /api/timer/start
     */
    @PostMapping("/start")
    public ApiResponse<TimeRecordResponse> startTimer(
            @Validated @RequestBody TimeRecordRequest request,
            HttpServletRequest httpRequest) {
        try {
            Long userId = (Long) httpRequest.getAttribute("userId");
            TimeRecordResponse response = timerService.startTimer(userId, request.getTaskId());
            return ResponseUtil.success("计时已开始", response);
        } catch (IllegalStateException | IllegalArgumentException e) {
            return ResponseUtil.error(e.getMessage());
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseUtil.serverError("开始计时失败");
        }
    }
    
    /**
     * 暂停计时
     * POST /api/timer/{recordId}/pause
     */
    @PostMapping("/{recordId}/pause")
    public ApiResponse<TimeRecordResponse> pauseTimer(
            @PathVariable Long recordId,
            HttpServletRequest request) {
        try {
            Long userId = (Long) request.getAttribute("userId");
            TimeRecordResponse response = timerService.pauseTimer(recordId, userId);
            return ResponseUtil.success("计时已暂停", response);
        } catch (IllegalArgumentException | IllegalStateException e) {
            return ResponseUtil.error(e.getMessage());
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseUtil.serverError("暂停计时失败");
        }
    }
    
    /**
     * 继续计时
     * POST /api/timer/{recordId}/resume
     */
    @PostMapping("/{recordId}/resume")
    public ApiResponse<TimeRecordResponse> resumeTimer(
            @PathVariable Long recordId,
            HttpServletRequest request) {
        try {
            Long userId = (Long) request.getAttribute("userId");
            TimeRecordResponse response = timerService.resumeTimer(recordId, userId);
            return ResponseUtil.success("计时已继续", response);
        } catch (IllegalArgumentException | IllegalStateException e) {
            return ResponseUtil.error(e.getMessage());
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseUtil.serverError("继续计时失败");
        }
    }
    
    /**
     * 停止计时
     * POST /api/timer/{recordId}/stop
     */
    @PostMapping("/{recordId}/stop")
    public ApiResponse<TimeRecordResponse> stopTimer(
            @PathVariable Long recordId,
            HttpServletRequest request) {
        try {
            Long userId = (Long) request.getAttribute("userId");
            TimeRecordResponse response = timerService.stopTimer(recordId, userId);
            return ResponseUtil.success("计时已停止", response);
        } catch (IllegalArgumentException | IllegalStateException e) {
            return ResponseUtil.error(e.getMessage());
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseUtil.serverError("停止计时失败");
        }
    }
    
    /**
     * 获取当前运行的计时器
     * GET /api/timer/current
     */
    @GetMapping("/current")
    public ApiResponse<TimeRecordResponse> getCurrentTimer(HttpServletRequest request) {
        try {
            Long userId = (Long) request.getAttribute("userId");
            TimeRecordResponse response = timerService.getCurrentTimer(userId);
            return ResponseUtil.success(response);
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseUtil.serverError("查询当前计时器失败");
        }
    }
    
    /**
     * 获取计时记录列表
     * GET /api/timer/records
     * 参数：taskId, startDate, endDate
     */
    @GetMapping("/records")
    public ApiResponse<List<TimeRecordResponse>> getTimeRecords(
            @RequestParam(required = false) Long taskId,
            @RequestParam(required = false) @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) LocalDate startDate,
            @RequestParam(required = false) @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) LocalDate endDate,
            HttpServletRequest request) {
        try {
            Long userId = (Long) request.getAttribute("userId");
            List<TimeRecordResponse> records = timerService.getTimeRecords(userId, taskId, startDate, endDate);
            return ResponseUtil.success(records);
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseUtil.serverError("查询计时记录失败");
        }
    }
    
    /**
     * 删除计时记录
     * DELETE /api/timer/records/{recordId}
     */
    @DeleteMapping("/records/{recordId}")
    public ApiResponse<Void> deleteTimeRecord(
            @PathVariable Long recordId,
            HttpServletRequest request) {
        try {
            Long userId = (Long) request.getAttribute("userId");
            timerService.deleteTimeRecord(recordId, userId);
            return ResponseUtil.success("删除成功");
        } catch (IllegalArgumentException e) {
            return ResponseUtil.error(e.getMessage());
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseUtil.serverError("删除计时记录失败");
        }
    }
    
    /**
     * 获取统计信息
     * GET /api/timer/statistics
     * 参数：period (today, week, month)
     */
    @GetMapping("/statistics")
    public ApiResponse<TimerStatistics> getStatistics(
            @RequestParam(required = false, defaultValue = "week") String period,
            HttpServletRequest request) {
        try {
            Long userId = (Long) request.getAttribute("userId");
            TimerStatistics statistics = timerService.getStatistics(userId, period);
            return ResponseUtil.success(statistics);
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseUtil.serverError("获取统计信息失败");
        }
    }
    
    /**
     * 获取汇总统计数据
     * GET /api/timer/statistics/summary
     * 参数：period, startDate, endDate
     */
    @GetMapping("/statistics/summary")
    public ApiResponse<com.taskmanager.dto.StatisticsSummaryDTO> getStatisticsSummary(
            @RequestParam(required = false, defaultValue = "week") String period,
            @RequestParam(required = false) @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) LocalDate startDate,
            @RequestParam(required = false) @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) LocalDate endDate,
            HttpServletRequest request) {
        try {
            Long userId = (Long) request.getAttribute("userId");
            
            // 根据period确定日期范围
            if (startDate == null || endDate == null) {
                endDate = LocalDate.now();
                switch (period) {
                    case "today":
                        startDate = LocalDate.now();
                        break;
                    case "week":
                        startDate = LocalDate.now().minusWeeks(1);
                        break;
                    case "month":
                        startDate = LocalDate.now().minusMonths(1);
                        break;
                    default:
                        startDate = LocalDate.now().minusWeeks(1);
                }
            }
            
            com.taskmanager.dto.StatisticsSummaryDTO summary = timerService.getDetailedStatistics(userId, startDate, endDate);
            return ResponseUtil.success(summary);
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseUtil.serverError("获取汇总统计失败");
        }
    }
    
    /**
     * 获取分类统计数据
     * GET /api/timer/statistics/category
     * 参数：period, startDate, endDate
     */
    @GetMapping("/statistics/category")
    public ApiResponse<List<com.taskmanager.dto.CategoryStatisticsDTO>> getCategoryStatistics(
            @RequestParam(required = false, defaultValue = "week") String period,
            @RequestParam(required = false) @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) LocalDate startDate,
            @RequestParam(required = false) @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) LocalDate endDate,
            HttpServletRequest request) {
        try {
            Long userId = (Long) request.getAttribute("userId");
            
            // 根据period确定日期范围
            if (startDate == null || endDate == null) {
                endDate = LocalDate.now();
                switch (period) {
                    case "today":
                        startDate = LocalDate.now();
                        break;
                    case "week":
                        startDate = LocalDate.now().minusWeeks(1);
                        break;
                    case "month":
                        startDate = LocalDate.now().minusMonths(1);
                        break;
                    default:
                        startDate = LocalDate.now().minusWeeks(1);
                }
            }
            
            List<com.taskmanager.dto.CategoryStatisticsDTO> statistics = timerService.getCategoryStatistics(userId, startDate, endDate);
            return ResponseUtil.success(statistics);
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseUtil.serverError("获取分类统计失败");
        }
    }
    
    /**
     * 获取每日趋势数据
     * GET /api/timer/statistics/daily
     * 参数：period, startDate, endDate
     */
    @GetMapping("/statistics/daily")
    public ApiResponse<List<com.taskmanager.dto.DailyTrendDTO>> getDailyTrendStatistics(
            @RequestParam(required = false, defaultValue = "week") String period,
            @RequestParam(required = false) @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) LocalDate startDate,
            @RequestParam(required = false) @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) LocalDate endDate,
            HttpServletRequest request) {
        try {
            Long userId = (Long) request.getAttribute("userId");
            
            // 根据period确定日期范围
            if (startDate == null || endDate == null) {
                endDate = LocalDate.now();
                switch (period) {
                    case "today":
                        startDate = LocalDate.now();
                        break;
                    case "week":
                        startDate = LocalDate.now().minusWeeks(1);
                        break;
                    case "month":
                        startDate = LocalDate.now().minusMonths(1);
                        break;
                    default:
                        startDate = LocalDate.now().minusWeeks(1);
                }
            }
            
            List<com.taskmanager.dto.DailyTrendDTO> trends = timerService.getDailyTrendStatistics(userId, startDate, endDate);
            return ResponseUtil.success(trends);
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseUtil.serverError("获取每日趋势失败");
        }
    }
    
    /**
     * 导出统计数据
     * GET /api/timer/statistics/export
     * 参数：period, startDate, endDate, format
     */
    @GetMapping("/statistics/export")
    public void exportStatistics(
            @RequestParam(required = false, defaultValue = "week") String period,
            @RequestParam(required = false) @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) LocalDate startDate,
            @RequestParam(required = false) @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) LocalDate endDate,
            @RequestParam(required = false, defaultValue = "csv") String format,
            HttpServletRequest request,
            javax.servlet.http.HttpServletResponse response) {
        try {
            Long userId = (Long) request.getAttribute("userId");
            
            // 根据period确定日期范围
            if (startDate == null || endDate == null) {
                endDate = LocalDate.now();
                switch (period) {
                    case "today":
                        startDate = LocalDate.now();
                        break;
                    case "week":
                        startDate = LocalDate.now().minusWeeks(1);
                        break;
                    case "month":
                        startDate = LocalDate.now().minusMonths(1);
                        break;
                    default:
                        startDate = LocalDate.now().minusWeeks(1);
                }
            }
            
            String csvData = timerService.exportStatisticsData(userId, startDate, endDate);
            
            // 设置响应头
            response.setContentType("text/csv;charset=UTF-8");
            response.setHeader("Content-Disposition", 
                "attachment; filename=statistics_" + LocalDate.now().toString() + ".csv");
            
            // 写入CSV数据
            response.getWriter().write("\uFEFF"); // UTF-8 BOM for Excel
            response.getWriter().write(csvData);
            response.getWriter().flush();
        } catch (Exception e) {
            e.printStackTrace();
            response.setStatus(javax.servlet.http.HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        }
    }
}
